var app = getApp()

import { homeCtrls, myorderIcon, mapHeight, markerTypes, mapType, ordersHeight, ctrlsType, bar_chuxing_act, bar_moren_act, bar_wuzhangai_act, getHomeCtrlsByMapType, freeBarrierHeight, showBarrierFreeDefaultScale, defaultScale, wsType, duration, extractHeight } from '../../config/config'
import { getMyOrder, getOrders, sendPosDataToSocket, getCoordinateCat, getFreeBarrierType, dataQuery, setParams, closeSocket } from '../../utils/apiFns'
import { navigateTo, redirectTo,relaunch, getMapCenter, getUserInfo, showLoading, showToast } from '../../utils/promiseFns'
import { transformPointsToMarkers, transformFreeBarrierPointsToMarkers, getCoorDataById, transformFacStrToArray, activeMarker } from '../../utils/util'


Page({
  data: {
    markers: [],
    controls: homeCtrls,
    mapHeight: mapHeight,
    orderList: [],
    coordList: [],
    markerType: markerTypes,
    mapType: mapType.showOrders,
    markerData: null,
    activeMarkerId: -1,
    longitude: 113.296315,
    latitude: 23.095781,
    coordCat: [],
    barrierType: [],
    isLoading: false,
    scale: 17
  },

  map: null,
  testCount: 0,
  setOrderDataMarkerInterval: null,
  onLoad() {

    this.map = wx.createMapContext('map');

    // this.showDefault();
    this.showAllOrders();

    this.initData();

    //获取地点类型
    getCoordinateCat().then(res => {

      this.setData({
        coordCat: res.data.result
      })
    })

    //获取无障碍类型
    getFreeBarrierType().then(res => {

      this.setData({
        barrierType: res.data.result
      })
    })

  },
  onShow() {

    var that = this;

    // wx.showModal({
    //   title:"提示:",
    //   content:"即将上线",
    //   confirmText:'知道了'
    // })

    wx.setNavigationBarTitle({
      title: '小水滴行动'
    })

    // 
    this.setData({
      controls: getHomeCtrlsByMapType(this.data.mapType, app.myorderData)
    })

    var that = this;

    // this.mapCtx.moveToLocation();
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: (res)=> {

        wx.hideToast();
        var latitude = res.latitude
        var longitude = res.longitude

        //that.map.moveToLocation()
        this.setData({
          longitude:longitude,
          latitude:latitude
        })

      }
    })


    //测试orders
    // this.showOrders()
    // setTimeout(()=>{
    //   this.showOrderDetial(1)
    // },100)

    //测试free
    // this.showBarrierFree();
    // setTimeout(() => {
    //   this.showBarrierFreeAct(14)
    // }, 2000)

  },

  regionchange(e) {

    if (e.type == 'end') {
      //用来获取当用户移动地图的时候，获取地图中点坐标
      if (this.data.mapType == mapType.showBarrierFree) {
        setTimeout(() => {
          this.showBarrierFree()
        }, 200)
      } else if (this.data.mapType == mapType.showOrders) {
        setTimeout(() => {
          this.showAllOrders()
        }, 200)
      }
    }
  },

  showBarrierFree() {

    this.setData({
      mapType: mapType.showBarrierFree,
      controls: getHomeCtrlsByMapType(mapType.showBarrierFree, app.myorderData)
    })

    this.setMarkersData(wsType.freeBarrier, transformFreeBarrierPointsToMarkers, this.data.coordCat, markerTypes.freeBarrier)

  },

  showAllOrders() {

    this.setData({
      mapType: mapType.showOrders,
      controls: getHomeCtrlsByMapType(mapType.showOrders, app.myorderData)
    })

    this.setMarkersData(wsType.allOrders, transformFreeBarrierPointsToMarkers, null, markerTypes.order, markerTypes.order_act)

    if (this.setOrderDataMarkerInterval == null) {

      this.setOrderDataMarkerInterval = setInterval(() => {

        this.setMarkersData(wsType.allOrders, transformFreeBarrierPointsToMarkers, null, markerTypes.order, markerTypes.order_act)

      }, 3000)

    }

  },

  setMarkersData(wsTypeName, transformFn, coordCat, markerTypeObj, markerActTypeObj) {

    getMapCenter(this.map).then(pos => {

      sendPosDataToSocket(pos, app, wsTypeName).then(re => {

        wx.onSocketMessage((res) => {

          var res = JSON.parse(res.data)

          var result = [];

          if (res.seqnum == app.seqnum) {

            result = res.result;

            console.log('result: ', result);

            var markers;

            if (result.length) {

              markers = transformFn(result, coordCat, this.data.activeMarkerId, markerTypeObj, markerActTypeObj);

            } else {

              markers = []

            }

            this.setData({
              markers: markers,
              coordList: result
            })

          }
          
          wx.hideLoading()

        })
        wx.hideLoading()

      });

    })

  },

  showDefault() {

    this.setData({
      // scale: defaultScale,
      markers: [],
      mapType: mapType.showDefault,
      controls: getHomeCtrlsByMapType(mapType.showDefault, app.myorderData)
    })
    // this.map.moveToLocation()
    wx.hideLoading()

  },

  markertap(e) {

    if (this.data.mapType == mapType.showOrders) {
      this.showOrderDetial(e.markerId)
    } else if (this.data.mapType == mapType.showBarrierFree) {
      this.showBarrierFreeAct(e.markerId)
    }
  },


  showBarrierFreeAct(id) {

    var newMarkers,
      actData,
      markerObj,
      newHeight;

    markerObj = {
      newMarkerList: [],
      activeItem: null
    }

    markerObj = activeMarker(this.data.markers, id, markerTypes.freeBarrierAct, markerTypes.freeBarrier)


    var queryParams = setParams('queryBarrierFreeDetails', {
      id: id
    });

    this.setData({
      isLoading: true,
      activeMarkerId: id
    })

    dataQuery(queryParams)().then(res => {


      actData = transformFacStrToArray(res.data.result, this.data.barrierType)

      if (!actData.tel) {

        newHeight = this.data.mapHeight + extractHeight;

      }

      this.setData({
        isLoading: false,
        markerData: actData,
        mapHeight: newHeight
      })
    })

    newHeight = mapHeight - freeBarrierHeight

    // if(!actData.tel){
    //   newHeight -= 14
    // }

    this.setData({
      markers: markerObj.newMarkerList,
      mapHeight: newHeight,
      latitude: markerObj.activeItem.latitude,
      longitude: markerObj.activeItem.longitude
    })

  },

  showOrderDetial(id) {

    var newMarkers,
      actData,
      markderObj;

    markderObj = {
      newMarkerList: [],
      activeItem: null
    }

    markderObj = activeMarker(this.data.markers, id, markerTypes.order_act, markerTypes.order);

    var queryParams = {
      service: 'service',
      api: 'queryServiceRequestTravel',
      version: 1,
      params: {
        id: id
      }
    }

    this.setData({
      isLoading: true,
      activeMarkerId: id,
      markers: markderObj.newMarkerList,
      latitude: markderObj.activeItem.latitude,
      longitude: markderObj.activeItem.longitude,
      mapHeight: mapHeight - ordersHeight,
    })

    dataQuery(queryParams)().then(res => {

      this.setData({
        isLoading: false,
        markerData: res.data.result,
      })

    })

  },

  initData() {

      showLoading()

    getUserInfo().then(res => {
      
      showLoading()

      var userParams = {
        service: 'weixin',
        api: 'wxLogin',
        version: 1,
        params: {
          code: res.code
        },
      }

      return dataQuery(userParams)()

    })
      //获取当前用户下过的订单id
      .then(res => {
        showLoading()

        app.user_token = res.data.token

        var myOrderParams = {
          service: 'service',
          api: 'queryOwnServiceRequest',
          version: 1,
          params: {
            token: app.user_token,
            duration: duration
          }
        }

        return dataQuery(myOrderParams)()

      })

      .then(res => {

        app.myorderData = res.data.result;

        this.setData({
          controls: getHomeCtrlsByMapType(this.data.mapType, app.myorderData)
        })

        setTimeout(()=>{
          wx.hideLoading()
        },1000)


        //TODO:
        // navigateTo('/pages/show_myorder/show_myorder')

      })

      .catch(err => {

        // showToast(err.toString())
        wx.hideLoading()
        showToast('获取用户信息失败,请重新进入小程序', '/resources/images/error3.png')

      })

  },

  clearDataWhenSwitch() {

    // showLoading('clear')

    if (this.setOrderDataMarkerInterval) {
      clearInterval(this.setOrderDataMarkerInterval);
    }

    this.setOrderDataMarkerInterval = null;

    this.setData({
      // markers: [],
      activeMarkerId: -1,
    // scale: showBarrierFreeDefaultScale
    })

  },

  controltap(e) {

    switch (e.controlId) {
      case ctrlsType.addInfo:
        this.clearDataWhenSwitch()
        navigateTo('/pages/order_add/order_add')
        break;

      case ctrlsType.moveToMe:
        this.map.moveToLocation();
        break;

      case ctrlsType.showOrders:
        if (this.data.mapType != mapType.showOrders) {
          this.clearDataWhenSwitch()
          // closeSocket().then(res => {
          this.showAllOrders()
        // })
        }
        break;

      case ctrlsType.showBarrierFree:
        if (this.data.mapType != mapType.showBarrierFree) {
          this.clearDataWhenSwitch()
          // closeSocket().then(res => {
          this.showBarrierFree()
        // })
        }
        break;

      case ctrlsType.showMyOrder:
        this.clearDataWhenSwitch()
        navigateTo('/pages/show_myorder/show_myorder');
        break;
      default:
        break;
    }

  },
  tapMap() {



    var markers = [];
    //假如当前是在无障碍地图上,清除激活状态的marker类型
    var markType = null;

    if (this.data.mapType == mapType.showBarrierFree) {
      markType = markerTypes.freeBarrier
    } else if (this.data.mapType == mapType.showOrders) {
      markType = markerTypes.order
    }

    if (markType) {

      if (this.data.activeMarkerId != -1) {

        markers = this.data.markers.map(item => {
          if (item.id == this.data.activeMarkerId) {
            item.iconPath = item.iconPath.replace('_act.png', '.png');
            item = Object.assign({}, item, markType);
          }
          return item
        })



        this.setData({
          markers: markers,
          activeMarkerId: -1,
          mapHeight: mapHeight
        })

      }

    }

  },

  makePhoneCall() {
    wx.makePhoneCall({
      phoneNumber: this.data.markerData.asker_phone
    })
  }

})